﻿using DiLe.Mes.Model.Common;
using MapleLeaf.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DiLe.Mes.Application {
    /// <summary>
    /// 编码
    /// </summary>
    public static class CodeHandler {
        /// <summary>
        /// 
        /// </summary>
        private readonly static object balanceLock = new();
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static string GetBusinessCode(string prefix) {
            string str;
            lock (balanceLock) {
                var m = SqlSugarHelper.MasterDb.Queryable<CodeRuleEntity>().First(p => p.Prefix == prefix);
                if (m == null) {
                    var t = new CodeRuleEntity {
                        SerialCode = 1,
                        DigitCapacity = 3,
                        Prefix = prefix,
                    };
                    m = SqlSugarHelper.MasterDb.Insertable(t).ExecuteReturnEntity();
                }
                var code = $"{m!.SerialCode}".PadLeft(m.DigitCapacity, '0');
                str = $"{m.Prefix}{DateTime.Now:yyyymmdd}{code}";
                m.SerialCode++;
                SqlSugarHelper.MasterDb.Updateable(m).ExecuteCommand();
            }
            return str;
        }
    }
}
